import os
import re
import sys
from pathlib import Path

def delete_problematic_lines(file_path):
    """删除文件中的问题行"""
    print(f"Processing file: {file_path}")
    
    # 尝试多种编码读取文件
    encodings = ['utf-8', 'gbk', 'gb2312', 'latin1', 'cp1252']
    content = None
    encoding_used = None
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            encoding_used = encoding
            print(f"  Successfully read with encoding: {encoding}")
            break
        except UnicodeDecodeError:
            continue
    
    if content is None:
        print(f"  Could not read file with any encoding")
        return False
    
    # 分割为行
    lines = content.split('\n')
    
    # 标记问题行 - 8863行（索引8862）
    problem_lines = [8862]  # 8863行的索引
    
    # 处理问题行
    fixed_lines = []
    for i, line in enumerate(lines):
        line_num = i + 1
        
        # 如果是问题行，删除它
        if i in problem_lines:
            print(f"    Line {line_num}: Deleting problematic line: {repr(line[:50])}")
            fixed_lines.append(f"// Line {line_num}: Original problematic line deleted")
            continue
        
        # 检查其他行的编码问题
        try:
            line.encode('utf-8')
            fixed_lines.append(line)
        except UnicodeEncodeError:
            # 如果不能编码为UTF-8，替换或删除该行
            print(f"    Line {line_num}: Contains non-UTF-8 characters, removing...")
            fixed_lines.append(f"// Line {line_num}: Original line contained non-UTF-8 characters")
    
    # 写回文件
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(fixed_lines))
        print(f"  Successfully fixed file")
        return True
    except Exception as e:
        print(f"  Error writing file: {e}")
        return False

def main():
    # 确定文件路径
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
    else:
        file_path = "gate-server/src/main/java/com/lastwar/gateserver/login/LoginHandler.java"
    
    if not os.path.isabs(file_path):
        script_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(script_dir, file_path)
    
    if os.path.isfile(file_path):
        delete_problematic_lines(file_path)
    else:
        print(f"File not found: {file_path}")

if __name__ == "__main__":
    main()